package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"oa_kadia_link/config"
	"oa_kadia_link/globe"
	"oa_kadia_link/middleware"
	"oa_kadia_link/router"
	"oa_kadia_link/utils"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 设置web服务访问日志文件
	access, err := os.Create("access.log")
	utils.CheckError(err)
	gin.DefaultWriter = io.MultiWriter(access)
	defer func() {
		utils.CheckError(access.Close())
	}()
	// 设置错误日志文件（nohup控制台）
	outAndErr, err := os.Create("out_and_error.log")
	utils.CheckError(err)
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	if !config.GetEnv().DevMode {
		log.SetOutput(outAndErr)
		os.Stdout = outAndErr
		os.Stderr = outAndErr
	}
	defer func() {
		utils.CheckError(outAndErr.Close())
	}()
	// 创建app
	app := gin.New()
	// 上传文件内存限制
	app.MaxMultipartMemory = config.GetEnv().UploadSize
	// 全局中间件
	app.Use(middleware.Logger(), middleware.Recovery(), middleware.ServerStatus(), middleware.Limiting(), middleware.CheckIp(), middleware.AccessOrigin())
	// 设置路由
	RouterSet(app)
	// 安全启动、安全退出
	RunAndQuitSafely(app)
}

func RouterSet(app *gin.Engine) {
	// 认证路由
	auth := app.Group("/auth")
	auth.Use(middleware.Transaction())
	router.Auth(auth)

	user := app.Group("/user")
	user.Use(middleware.CheckToken("user"),middleware.Transaction())
	router.User(user)
}

func RunAndQuitSafely(app *gin.Engine) {
	defer func() {
		utils.CheckError(globe.CloseDB())
	}()
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%s", config.GetEnv().Port),
		Handler: app,
	}
	// Run线程
	go func() {
		log.Println("Server running...")
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Panicln(err)
		}
	}()
	// 等待信号
	signal.Ignore(syscall.SIGHUP, syscall.SIGPIPE)
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	// 开始关闭
	log.Println("Shutdown...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	// 关闭监听并等待已有连接结束
	if err := srv.Shutdown(ctx); err != nil {
		log.Panicln("Shutdown err:", err)
	}
	log.Println("Server exiting safely")
}